package com.example.springbootdemo.text;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 使用Jaccard相似系数
 * Jaccard相似系数是用于比较有限样本集之间相似性的统计学方法。它定义为两个集合交集大小除以并集大小
 */
public class JaccardSimilarity {
    public static double compute(String s1, String s2) {
        Set<String> set1 = new HashSet<>(Arrays.asList(s1.split(" ")));
        Set<String> set2 = new HashSet<>(Arrays.asList(s2.split(" ")));

        Set<String> intersection = new HashSet<>(set1);
        intersection.retainAll(set2);

        Set<String> union = new HashSet<>(set1);
        union.addAll(set2);

        return (double) intersection.size() / union.size();
    }

    public static double compute(Set<String> set1, Set<String> set2) {
//        Set<String> set1 = new HashSet<>(Arrays.asList(s1.split(" ")));
//        Set<String> set2 = new HashSet<>(Arrays.asList(s2.split(" ")));

        Set<String> intersection = new HashSet<>(set1);
        intersection.retainAll(set2);

        Set<String> union = new HashSet<>(set1);
        union.addAll(set2);

        return (double) intersection.size() / union.size();
    }

    public static void main(String[] args) {
        System.out.println(compute("apple banana orange", "banana kiwi apple")); // 输出: 0.5
    }
}